package net.atomtree.corrsepond.spider.service;

import net.atomtree.corrsepond.spider.SpiderContext;
import net.atomtree.corrsepond.spider.passage.PassageStrategy;
import net.atomtree.corrsepond.spider.passage.RunningApplicationPassage;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Created by czk on 2016/1/5.
 */
public class RunningApplicationService {

    public String getPort(SpiderContext context) throws Exception {
        Elements runApp= new PassageStrategy(new RunningApplicationPassage()).getPassage(context);
        String valAppId=context.param.get("appId").trim();
        System.out.println(valAppId);
        if(null!=valAppId||!valAppId.equals("")) {
            Elements trEls = runApp.get(0).getElementsByTag("tr");
            String portUrl = new String();
            //遍历每一行记录
            for (Element e1 : trEls) {
                Elements tdEls = e1.getElementsByTag("td");
                //只要遍历第一个td字段
                Elements appIdElements = tdEls.get(0).child(0).getElementsContainingText("app");
                System.out.println(appIdElements);
                for (Element element : appIdElements) {
                    //得到这一行的appID是否和我页面传来的ID是否相等
                    System.out.println("element.text().trim():"+element.text().trim());
                    if (element.text().trim().equals(valAppId)) {
                        System.out.println("找到了" + valAppId);
                        //得到appID相应的url端口
                        portUrl = tdEls.get(1).child(0).attr("href");
                        String port=portUrl.substring(portUrl.lastIndexOf(":")+1);
                        System.out.println(valAppId + "端口号为" + portUrl);
                        return port;
                    } else {
                        System.out.println("没找到" + valAppId);
                        return "0000";
                    }
                }
            }
        }
        throw new Exception("appId为空找不到对应的端口,任务可能已经完成");
    }

    public String getAppName(String jobId){
        return "Spark%20Pi";
    }

    public String getPort(String appId) throws Exception {
        SpiderContext context=new SpiderContext();
        context.param.put("appId",appId);
        context.host="101.204.243.107";
        context.url="http://101.204.243.107:8080/";
        return getPort(context);
    }


    public static void main(String[] args) throws Exception {
        SpiderContext context=new SpiderContext();
        context.url="http://101.204.243.107:8080/";
        context.param.put("appId","app-20160105150153-0013 ");
        RunningApplicationService runningApplicationService=new RunningApplicationService();
        String port=runningApplicationService.getPort(context);
        System.out.println("port:"+port);
    }
}
